package com.scap.dfs.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.scap.dfs.dao.AccountDao;
import com.scap.dfs.entity.Account;
import com.scap.dfs.service.AccountService;

@Service("accountService")
@Transactional
public class AccountServiceImple implements AccountService {

	@Autowired
	private AccountDao voAccount;
	
	@Autowired
	private ApplicationContext context;

	@Override
	public List<Object> findByAll() {
		return this.voAccount.findByAll();
	}

	@Override
	public String insert(Account voAccount, BindingResult result,
			HttpServletRequest request) {
	
		String vnResult =  "";
		Locale voLocale = RequestContextUtils.getLocale(request);
		
		if (this.voAccount.insert(voAccount)) {
			vnResult = context.getMessage("alert.save.success", null, voLocale);
		} else {
			vnResult = context.getMessage("alert.save.fail", null, voLocale);
		}
		
		return vnResult;
	}

	@Override
	public String update(Account voAccount, BindingResult result,
			HttpServletRequest request) {
		
		String vnResult =  "";
		Locale voLocale = RequestContextUtils.getLocale(request);
		
		if (this.voAccount.update(voAccount)) {
			vnResult = context.getMessage("alert.save.success", null, voLocale);
		} else {
			vnResult = context.getMessage("alert.save.fail", null, voLocale);
		}
		
		return vnResult;
		
	}

	@Override
	public String delete(Account voAccount, HttpServletRequest request) {
		
		String vnResult =  "";
		Locale voLocale = RequestContextUtils.getLocale(request);
		
		if (this.voAccount.update(voAccount)) {
			vnResult = context.getMessage("alert.save.success", null, voLocale);
		} else {
			vnResult = context.getMessage("alert.save.fail", null, voLocale);
		}
		return vnResult;
		
	}

	
	@Override
	public List<Object> getListBasedOnSearchParameter(String searchParameter,
			List<Object> accountList) {
		
		if (null != searchParameter && !searchParameter.equals("")) {
			List<Object> accountForSearch = new ArrayList<Object>();
			searchParameter = searchParameter.toUpperCase();
			for (int i=0; i<accountList.size(); i++) {
				
				Account account = (Account) findByAll().get(i);
				if (account.getVaAccountCode().toUpperCase().indexOf(searchParameter)!= -1 || account.getVaAccountDescription().toUpperCase().indexOf(searchParameter)!= -1 ) {
					accountForSearch.add(accountList);					
				}
				
			}
			accountList = accountForSearch;
			accountForSearch = null;
		}
		return accountList;
	
	}
	
}
